package cron.core.scheduler.timer;


import cn.hutool.core.collection.ConcurrentHashSet;
import cron.core.scheduler.trigger.Trigger;

import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.Executor;

/**
 * 超时任务触发器容器
 * @author : willian fu
 * @version : 1.0
 * @date : 2021/3/9 0009 10:48
 */
public class Bucket {

    //存储所有满足条件的触发器
    private Set<Trigger> triggers;

    /**
     * 添加一个触发器
     * @param trigger 触发器
     */
    public void addTrigger(Trigger trigger){
        if (null == triggers){
            triggers = new ConcurrentHashSet<>();
        }
        triggers.add(trigger);
    }

    public void removeTrigger(Trigger trigger){
        if (null != triggers){
            triggers.remove(trigger);
        }
    }

    /**
     * 执行所有触发器超时任务
     * @param executor 线程池
     */
    public void doRun(Executor executor, long count){
        if (null != triggers){
            triggers.forEach(trigger -> {
                if (trigger.isBeTrigger(count)){
                    executor.execute(trigger);
                }
            });
        }
    }
}
